/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.common.biz.config;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 事件异步线程配置
 * @author zhanghongyi
 * @date 2024/7/5 16:44
 * @description BizEventAsyncThreadPoolConfig
 */
@EnableAsync
@Configuration
public class BizEventAsyncThreadPoolConfig {

    /**
     * 自定义异步执行使用的线程池保证上下文的传递
     */
    @Bean("bizEventListenerAsyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(20);
        executor.setKeepAliveSeconds(60);
        executor.setQueueCapacity(1000);
        executor.setTaskDecorator(runnable -> {
            try {
                //获取父线程的context
                RequestAttributes context = RequestContextHolder.currentRequestAttributes();
                Map<String, String> mdcContextMap = MDC.getCopyOfContextMap();
                return () -> {
                    try {
                        //将父线程的context设置进子线程里
                        MDC.clear();
                        if (mdcContextMap != null) {
                            MDC.setContextMap(mdcContextMap);
                        }
                        RequestContextHolder.setRequestAttributes(context);
                        //子线程方法执行
                        runnable.run();
                    } finally {
                        //清除子线程context
                        MDC.clear();
                        RequestContextHolder.resetRequestAttributes();
                    }
                };
            } catch (IllegalStateException e) {
                return runnable;
            }
        });
        executor.setThreadNamePrefix("BizEventAsync-Pool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
